/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org	
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class CallLogHistory extends JustDroidActivity {
	private TextView txtContactName;
	private ListView callLogHistoryListView;
	private CommonAdapter callLogHistoryAdapter;
	private Runnable runnable;
	@SuppressWarnings("unused")
	private String number, id;
	private Handler handler;
	
	/** Function to run a thread to retrieve the call history associated with a number **/
	void runThread(final String number) {
		runnable = new Runnable() {
			@Override
			public void run() {
				getCallHistory(number);
			}
		};
		new Thread(runnable).start();
	}

	/** Function to retrieve the call history associated with a number **/
	@SuppressLint("SimpleDateFormat")
	void getCallHistory(String num) {
		Cursor cursor = getContentResolver().query(Uri.parse("content://call_log/calls"), null, CallLog.Calls.NUMBER + " = ?", 
				new String[]{num}, "date DESC");
		int i = 0;
		Message message = new Message();
		Bundle bundle = new Bundle();
		while(cursor.moveToNext()) {
			Bundle values = new Bundle();
			if(cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE)) != null) {
				Date date = new Date(Long.valueOf(cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE))));
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy' 'HH:MM:ss");
				values.putString("date", Html.fromHtml("<br/>") + simpleDateFormat.format(date) + " ");
			}
			else
				values.putString("date", "");
			if(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL)) != null) {
				String type = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL));
				values.putString("type", type);
			}
			else
				values.putString("type", "");
			values.putInt("status", cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)));
			bundle.putBundle(Integer.toString(i), values);
			i++;
		}
		message.setData(bundle);
		handler.sendMessage(message);
	}	
	
	/** Create the Call Log activity **/
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.callloghistory);
		super.onCreate(savedInstanceState);

		// Currently, do not know how to write the code that implements lateral navigation to swipe via tabs
		// as described at http://developer.android.com/training/implementing-navigation/lateral.html,
		// since swiping has already been implemented for the home screens
		
		/** Find UI elements **/
		txtContactName = (TextView) findViewById(R.id.txtContactName);
		callLogHistoryListView = (ListView) findViewById(R.id.lstCallLogHistory);
		
		/** Handle click events **/
		/*callLogHistoryListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				//vibrate
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(200);
				//TTS.speak(callLogHistoryAdapter.getItem(position).toString());
			}
		});*/
		
		/*txtContactName.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(((TextView)view).getText().toString());
				return false;
			}
		});*/
	
		//retrieve the passed number
		this.number = getIntent().getExtras().getString("number");
		this.id = getIntent().getExtras().getString("id");
		if(getIntent().getExtras().getString("name") != null)
			txtContactName.setText(getIntent().getExtras().getString("name"));
		else
			txtContactName.setText(getIntent().getExtras().getString("number"));
		
		runThread(this.number);
				
		handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				
				ArrayList<String> strRecords = new ArrayList<String>();
				Bundle bundle = message.getData();
				if(bundle.size() == 0) {
					//empty log
					if(Utils.isAccessibilityEnabled(getApplicationContext()))
						TTS.speak(getResources().getString(R.string.emptylog));
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.emptylog), Toast.LENGTH_SHORT).show();
				}
				else {
						for(int i=0; i<bundle.size(); i++) {
							Bundle tempBundle = bundle.getBundle(Integer.toString(i));
							String status = "";
							switch(tempBundle.getInt("status")) {
							case CallLog.Calls.INCOMING_TYPE:
								status = "Received";
								break;
							case CallLog.Calls.MISSED_TYPE:
								status = "Missed";
								break;
							case CallLog.Calls.OUTGOING_TYPE:
								status = "Dialled";
								break;
							}
							strRecords.add(tempBundle.getString("date") + tempBundle.getString("type") + " " + status );
						}
				}
				callLogHistoryAdapter = new CommonAdapter(getApplicationContext(), strRecords);
				callLogHistoryListView.setAdapter(callLogHistoryAdapter);
			}
		};
		
		/** Put most everything before here **/
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.callloghistory);
		Utils.applyFontColorChanges(getApplicationContext(), layout);  Utils.applyFontSizeChanges(getApplicationContext(), layout);  Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}